/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-12 21:27:45
 * @LastEditTime: 2025-06-12 19:55:27
 * @FilePath: /monitor_belt/src/views/image/index.tsx
 */
/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-12-12 21:27:45
 * @LastEditTime: 2024-12-14 13:23:28
 * @FilePath: /monitor_belt/src/views/history/index.tsx
 */

import TableSearch from "@/components/table_search"
import { DatePicker, Flex, Input, message, Modal, Select, Table } from "antd"
import styles from './index.module.scss'
import SearchItem from "@/components/search_item"
import { columns } from "./column"
import { useEffect, useRef, useState } from "react"
import { isValidKey } from "@/utils"
import { getRowClassName, getTableScroll } from "@/utils/table"
import { disabledDate, getNowTimeKey } from "@/utils/date"
import { alarmTypes } from "@/utils/dictionary"
import { remoteAlarmList, updateAlarmState } from "@/api/message"
import { TAction } from "./index.type"
import { remoteImgQuery, remoteVideoQuery } from "@/api/picture"

const History = () => {
  //搜索初始化
  const searchParams: any = {
    alarm_type: undefined,
    date:undefined,
    dev_id: '',
    page: 1,
  }
  const formRef = useRef<any>();
  const [form, setForm] = useState<any>({ ...searchParams,size: 10 });
  const [scrollY, setScrollY] = useState(0)
  //加载状态
  const [loading, setLoading] = useState<boolean>(false);
  //数据列表
  const [list, setList] = useState<any[]>([]);
  //数据总数
  const [total, setTotal] = useState<number>(0);
  const [key, setKey] = useState<string>('');

  useEffect(() => {
    setScrollY(getTableScroll())
    formRef.current = { ...form };
    search();
  }, [])

  const search = async(page?: number) => {
    setLoading(true);
    setList([]);
    try {
      let newForm = { ...form, ...formRef.current };
      if (page) {
        changeItem(page, "page");
        newForm.page = page;
      }
      let res = await remoteVideoQuery(newForm);
      let { records=[],total } = res.data;
      setList(records || []);
      setTotal(total || 0);
    } finally {
      setLoading(false);
    }
  }

  //重置
  const reset = () => {
    for (let k in searchParams) {
      if (isValidKey(k, searchParams)) {
        formRef.current[k] = searchParams[k]
      }
    }
    setKey(getNowTimeKey())
    setForm(formRef.current);
    search(1);
  }
  //切换页数
  const changePage = (e: any) => {
    changeItem(e, 'page')
    search(e)
  }
  //参数变化
  const changeItem = (value: any, type: string) => {
    setForm({
      ...form,
      [type]: value
    })
    formRef.current[type] = value
  }
  //选择日期
  const changeDays = (dateStrings: [string, string]) => {
    let startDate = dateStrings[0]
    let endDate = dateStrings[1]
    changeItem(startDate + ' 00:00:00', 'startTime')
    changeItem(endDate + ' 23:59:59', 'endTime')
  }

  const dealInfo = async(row:any,type:TAction)=>{
    switch (type) {
      case TAction.RELEASE:
        Modal.confirm({
          title:"操作提示",
          content:"确定解除预警？",
          onOk:async()=>{
            await updateAlarmState({id:row.id})
            message.success("操作成功")
            search()
          }
        })
        break;
    
      default:
        break;
    }
  }

  return (
    <Flex gap={20} vertical flex={1} className={styles.wrapper}>
      <TableSearch isExtra={false} search={() => search(1)}
        reset={() => reset()}>
        <SearchItem title="设备编码">
          <Input
            allowClear
            placeholder="请输入设备编码"
            value={formRef.current?.dev_id}
            onChange={(e) => changeItem(e.target.value, 'dev_id')}
            style={{ width: '180px' }}
            />
        </SearchItem>
        <SearchItem title="事件类型">
          <Select
            allowClear
            placeholder="请选择事件类型"
            value={formRef.current?.alarm_type}
            onChange={(e) => changeItem(e, 'alarm_type')}
            style={{ width: '180px' }}
            options={[...alarmTypes]} />
        </SearchItem>
        <SearchItem title="发生时间">
          <DatePicker style={{width:'180px'}} key={key} onChange={(_e,d)=>changeItem(d,'date')} disabledDate={disabledDate} />
        </SearchItem>
      </TableSearch>
      <Flex>
      <Table
        columns={columns((row:any,type:TAction)=>dealInfo(row,type))}
        dataSource={list}
        loading={loading}
        rowKey={'id'}
        // sticky
        virtual
        scroll={{ x: 1000, y: scrollY }}
        rowClassName={getRowClassName}
        pagination={{
          size: formRef.current?.size,
          current: formRef.current?.page,
          total: total,
          showSizeChanger: true,
          onShowSizeChange: (_current: number, size: number) => changeItem(size, 'size'),
          showTotal: () => `共${total} 条`,
        }}
        onChange={(val) => changePage(val.current)}
      ></Table>
      </Flex>
    </Flex>
  )
}

export default History